import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Input, Carousel, Spin, Badge } from 'antd';
import { SearchOutlined, FireOutlined, EnvironmentOutlined } from '@ant-design/icons';
import { productAPI, bannerAPI, categoryAPI } from '../../services/api';
import { addToBrowseHistory, getCart } from '../../utils/storage';
import { message } from '../../utils/message';
import './Home.css';

const { Search } = Input;

const MobileHome = () => {
  const navigate = useNavigate();
  const [products, setProducts] = useState([]);
  const [banners, setBanners] = useState([]);
  const [categories, setCategories] = useState([]);
  const [hotProducts, setHotProducts] = useState([]);
  const [topSellingProducts, setTopSellingProducts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [showBackToTop, setShowBackToTop] = useState(false);
  const cart = getCart();
  const cartCount = cart.length; // 显示商品种类数，不是总数量

  // 获取轮播图数据
  useEffect(() => {
    const fetchBanners = async () => {
      try {
        const response = await bannerAPI.getBanners();
        if (response.success) {
          setBanners(response.data);
        }
      } catch (error) {
        console.error('获取轮播图失败:', error);
      }
    };

    fetchBanners();
  }, []);

  // 获取分类数据
  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await categoryAPI.getCategories();
        if (response.success) {
          setCategories(response.data.slice(0, 8)); // 只显示前8个分类
        }
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    };

    fetchCategories();
  }, []);

  // 获取商品数据
  const fetchProducts = useCallback(async (pageNum = 1, keyword = '') => {
    if (loading) return;
    
    setLoading(true);
    try {
      const response = await productAPI.getProducts({
        page: pageNum,
        pageSize: 10,
        keyword,
        includeInactive: false // 前台只显示上架商品
      });
      
      if (response.success) {
        const newProducts = response.data.list;
        if (pageNum === 1) {
          setProducts(newProducts);
          // 设置热门商品（销量最高的前4个）
          const sorted = [...newProducts].sort((a, b) => (b.sales || 0) - (a.sales || 0));
          setHotProducts(sorted.slice(0, 4));
          // 设置销量排名前三的商品用于轮播图
          setTopSellingProducts(sorted.slice(0, 3));
        } else {
          setProducts(prev => [...prev, ...newProducts]);
        }
        
        setHasMore(newProducts.length === 10);
        setPage(pageNum);
      }
    } catch (error) {
      message.error('获取商品数据失败');
    } finally {
      setLoading(false);
    }
  }, [loading]);

  // 初始加载
  useEffect(() => {
    fetchProducts(1, searchKeyword);
  }, [searchKeyword]);

  // 搜索处理
  const handleSearch = (value) => {
    // 当搜索框为空，重置搜索，显示所有商品
    if (!value.trim() && searchKeyword) {
      setSearchKeyword('');
      setPage(1);
      return;
    }
    
    if (value.trim()) {
      setSearchKeyword(value.trim());
      setPage(1);
    }
  };

  // 加载更多
  const loadMore = () => {
    if (hasMore && !loading) {
      fetchProducts(page + 1, searchKeyword);
    }
  };

  // 滚动监听
  useEffect(() => {
    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
      
      // 控制回到顶部按钮显示
      setShowBackToTop(scrollTop > 300);
      
      // 自动加载更多
      if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadMore();
      }
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [hasMore, loading, page, searchKeyword]);

  // 商品点击处理
  const handleProductClick = (product) => {
    addToBrowseHistory(product);
    navigate(`/app/product/${product.id}`);
  };

  // 分类点击处理
  const handleCategoryClick = (categoryId) => {
    navigate(`/app/category/${categoryId}`);
  };

  // 回到顶部功能
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
  };

  return (
    <div className="home-container">
      {/* 顶部搜索和位置栏 */}
      <div className="home-header">
        <div className="location-bar">
          <EnvironmentOutlined style={{ color: '#fff', marginRight: '4px', fontSize: '16px' }} />
          <span className="location-text" style={{ color: '#fff', fontWeight: '500' }}>北京市朝阳区</span>
        </div>
        <div className="search-section">
          <Search
            placeholder="搜索商品、品牌、分类"
            allowClear
            enterButton={<SearchOutlined style={{ fontSize: '16px' }} />}
            onSearch={handleSearch}
            className="home-search"
          />
          <Badge count={cartCount} size="small" style={{ backgroundColor: '#ff4d4f'}}>
            <div 
              className="cart-icon"
              onClick={() => navigate('/app/cart')}
              style={{
                backgroundColor: 'rgba(255,255,255,0.25)',
                color: '#fff',
                width: '32px',
                height: '32px',
                fontSize: '18px',
                boxShadow: '0 2px 6px rgba(0,0,0,0.1)',
                marginTop: '-5px',
                marginLeft: '-10px'
              }}
            >
              🛒
            </div>
          </Badge>
        </div>
      </div>

      {/* 轮播图区域 */}
      {topSellingProducts.length > 0 ? (
        <div className="banner-section">
          <Carousel autoplay dots={{ className: 'banner-dots' }}>
            {topSellingProducts.map((product, index) => (
              <div key={product.id} className="banner-item" onClick={() => handleProductClick(product)}>
                <div className="banner-content">
                  <div className='banner-image-container' style={{width: '100%', height: '100%'}}>
                    <img 
                      src={product.images[0]} 
                      alt={product.name}
                      className="banner-image"
                    />
                    </div>
                  <div className="banner-overlay">
                    <div className="banner-badge">销量榜 #{index + 1}</div>
                    <div className="banner-title">{product.name}</div>
                    <div className="banner-sales">已售 {product.sales}+</div>
                    <br/>
                  </div>
                </div>
              </div>
            ))}
          </Carousel>
        </div>
      ) : banners.length > 0 && (
        <div className="banner-section">
          <Carousel autoplay dots={{ className: 'banner-dots' }}>
            {banners.map(banner => (
              <div key={banner.id} className="banner-item">
                <img 
                  src={banner.image} 
                  alt={banner.title}
                  className="banner-image"
                />
              </div>
            ))}
          </Carousel>
        </div>
      )}

      {/* 分类导航 */}
      {categories.length > 0 && (
        <div className="category-section">
          <div className="category-grid">
            {categories.map(category => (
              <div 
                key={category.id}
                className="category-item"
                onClick={() => handleCategoryClick(category.id)}
              >
                <div className="category-icon">{category.icon}</div>
                <span className="category-name">{category.name}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 热门推荐 */}
      {hotProducts.length > 0 && (
        <div className="hot-section">
          <div className="section-header">
            <FireOutlined style={{ color: '#ff6b35', marginRight: '8px' }} />
            <span className="section-title">热门推荐</span>
          </div>
          <div className="hot-products">
            {hotProducts.map(product => (
              <div 
                key={product.id}
                className="hot-product-item"
                onClick={() => handleProductClick(product)}
              >
                <img 
                  src={product.images[0]} 
                  alt={product.name}
                  className="hot-product-image"
                />
                <div className="hot-product-info">
                  <div className="hot-product-name">{product.name}</div>
                  <div className="hot-product-price">¥{product.price}</div>
                  <div className="hot-product-sales">已售 {product.sales}+</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 商品瀑布流 */}
      <div className="products-section">
        <div className="section-header">
          <span className="section-title">为你推荐</span>
        </div>
        <div className="waterfall-container">
          <div className="waterfall-column">
            {products.filter((_, index) => index % 2 === 0).map(product => (
              <div 
                key={product.id} 
                className="product-card"
                onClick={() => handleProductClick(product)}
              >
                <img 
                  src={product.images[0]} 
                  alt={product.name}
                  className="product-image"
                  style={{ height: Math.random() * 80 + 180 }}
                />
                <div className="product-info">
                  <div className="product-name">{product.name}</div>
                  <div className="product-price">¥{product.price}</div>
                  <div className="product-sales">已售 {product.sales}+</div>
                </div>
              </div>
            ))}
          </div>
          <div className="waterfall-column">
            {products.filter((_, index) => index % 2 === 1).map(product => (
              <div 
                key={product.id} 
                className="product-card"
                onClick={() => handleProductClick(product)}
              >
                <img 
                  src={product.images[0]} 
                  alt={product.name}
                  className="product-image"
                  style={{ height: Math.random() * 80 + 180 }}
                />
                <div className="product-info">
                  <div className="product-name">{product.name}</div>
                  <div className="product-price">¥{product.price}</div>
                  <div className="product-sales">已售 {product.sales}+</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* 加载状态 */}
      {loading && (
        <div className="loading-section">
          <Spin size="large" />
        </div>
      )}

      {/* 没有更多数据提示 */}
      {!hasMore && products.length > 0 && (
        <div className="no-more-section">
          没有更多商品了~
        </div>
      )}

      {/* 回到顶部按钮 */}
      {showBackToTop && (
        <div className="back-to-top" onClick={scrollToTop}>
          ⬆️
        </div>
      )}
    </div>
  );
};

export default MobileHome; 